package com.rfid.a252robot.net;

import android.text.TextUtils;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.rfid.a252robot.BuildConfig;
import com.rfid.a252robot.net.bean.Respon;
import com.rfid.a252robot.net.bean.UploadBook;
import com.rfid.common.log.LogUtils;
import com.rfid.db.bean.Book;
import com.rfid.manager.DBManager;
import com.rfid.util.OkHttpUtils;
import com.spectre.generate.ConfigManager;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public enum  BoxLibApi {

    INSTANCE;

    IBoxService mApiService;

    public void init() {
        try {
            String url = ConfigManager.INSTANCE.getGlobalConfig().getShelfUrl();
            if (TextUtils.isEmpty(url)) {
                url = "http://192.168.2.16:8080";
            }
            if (!url.endsWith("/")) {
                url = url + "/";
            }
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
                    .client(OkHttpUtils.getClient())
                    .build();
            mApiService = retrofit.create(IBoxService.class);
        } catch (Exception e) {
            LogUtils.e(e);
        }
    }

    public void uploadBook(Book book,int type) throws IOException {
        UploadBook ub = new UploadBook();
        ub.setBarCode(book.getBarcode());
        ub.setBookName(book.getName());
        ub.setBoxNum(book.getBoxNum());
        ub.setReaderType(type);
        ub.setCabinet(ConfigManager.INSTANCE.getGlobalConfig().getCabinet());
        Call<Respon> responCall =  mApiService.uploadBookBox(ub);
        Respon respon =responCall.execute().body();
        LogUtils.v("uploadBook respon = " + respon);
    }

    public void deleteBook(Book book,int type) throws IOException {
        UploadBook ub = new UploadBook();
        ub.setBarCode(book.getBarcode());
        ub.setBookName(book.getName());
        ub.setBoxNum(book.getBoxNum());
        ub.setReaderType(type);
        ub.setCabinet(ConfigManager.INSTANCE.getGlobalConfig().getCabinet());
        Call<Respon> responCall =  mApiService.deleteBookBox(ub);
        Respon respon =responCall.execute().body();
        System.out.println(respon);
    }

    public String getBookByCode(String code) throws IOException {
        Call<Respon>  call = mApiService.getBookByCode(code);
        Respon respon =call.execute().body();
        if (respon.getCode() == 200) {
            String barcode = respon.getMsg();
            return barcode;
        }
        return "";

    }

}
